package com.wlbx.agent.global;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.tencent.mmkv.MMKV;
import com.wlbx.agent.BuildConfig;
import com.wlbx.agent.base.BaseActivity;
import com.wlbx.agent.bean.AccountInfoBean;
import com.wlbx.agent.net.IQuitToLogin;
import com.wlbx.agent.net.RequestManager;
import com.wlbx.agent.net.RetrofitManager;
//import com.wlbx.agent.ui.activity.LoginActivity;
import com.wlbx.agent.util.ActivityUtil;
import com.wlbx.agent.util.CommonUtil;
import com.wlbx.agent.util.SPUtil;
import com.wlbx.agent.util.spiderman.SpiderMan;

import cn.jpush.android.api.JPushInterface;

public class App extends Application implements IQuitToLogin {

    private static final String TAG = "App";
    private static App sApp;
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        sApp = this;
        //放在其他库初始化前
        context = getApplicationContext();
        initCrash();
        initRetrofit();
        initLoginStatus();
        initLog();
//        initBugly();
        initJPush();
        initMMKV();

        //监听退出到登录界面（单点登录）
        BaseActivity.addQuitToLoginListener(this);
    }

    private void initMMKV() {
        String rootDir = MMKV.initialize(this);
       Logger.i("mmkv root: " + rootDir);
    }

    private void initJPush() {
//        if (BuildConfig.LOG_DEBUG) {
//            JPushInterface.setDebugMode(true);
//        } else {
//            JPushInterface.setDebugMode(false);
//        }
//        JPushInterface.init(this);
//        String registrationId = JPushInterface.getRegistrationID(getApplicationContext());
//        SPUtil.putValue(Constant.USER_INFO, Constant.DEVICE_TOKEN, registrationId);
//        Logger.i(TAG, "registrationId---" + registrationId);
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }

    /**
     * 获取MyApplication实例
     */
    public static App getInstance() {
        return sApp;
    }

    private void initCrash() {
        if (BuildConfig.CRASH_DEBUG) {
            SpiderMan.init(sApp);
        }
    }

    /**
     * 初始Retrofit
     */
    private void initRetrofit() {
        RequestManager.mRetrofitManager = new RetrofitManager.Builder()
                .baseUrl(RequestManager.mBaseUrl)
                .connectTimeout(20 * 1000)
                .readTimeout(20 * 1000)
                .writeTimeout(20 * 1000)
                .build();
    }







//    private void initBugly() {
//        CrashReport.initCrashReport(getApplicationContext(), "189edcfa8c", BuildConfig.LOG_DEBUG);
//        Bugly.init(getApplicationContext(), "189edcfa8c", BuildConfig.LOG_DEBUG);
//    }


    private void initLog() {
        //初始化日志
//        Logger.init(getPackageName()).hideThreadInfo();
//        if (BuildConfig.LOG_DEBUG) {
//            //Debug,打印日志
//            Logger.init("AppPlusLog").setMethodCount(2).setLogLevel(LogLevel.FULL);
//        } else {
//            //release,关闭日志
//            Logger.init("AppPlusLog").setMethodCount(2).setLogLevel(LogLevel.NONE);
//        }
        Logger.addLogAdapter(new AndroidLogAdapter());
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(0)         // (Optional) How many method line to show. Default 2
                .methodOffset(7)        // (Optional) Hides internal method calls up to offset. Default 5
                .tag("wl")  // (Optional) Global tag for every log. Default PRETTY_LOGGER
                .build();

        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
        Logger.addLogAdapter(new AndroidLogAdapter() {
            @Override public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });
    }

    private void initLoginStatus() { //保存登录状态
        String userBase64 = (String) SPUtil.get(Constant.USER_INFO, "");
        if (!"".equals(userBase64)) {
            AccountManager.sUserBean = (AccountInfoBean) CommonUtil.base64ToObject(userBase64);
        }
    }


    /**
     * 发出退出App的消息。目前的使用场景是单点登录
     */
    public static void sendQuitBroadcast() {
        if (null == getInstance()) {
            return;
        }
        LocalBroadcastManager broadcastMgr = LocalBroadcastManager.getInstance(App.getInstance());
        broadcastMgr.sendBroadcast(new Intent("quit_single_sign_on"));
        return;
    }


    @Override
    public void onQuitToLogin(BaseActivity fromActivity, int reason) {
        AccountManager.removeSP();
        Logger.i(TAG, "quit app by callback in App...");
        BaseActivity.removeQuitToLoginListern();
//        Intent intent;
//        intent = new Intent(fromActivity, LoginActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(intent);
        if (ActivityUtil.getInstance().mActivityStack != null) {
            synchronized (ActivityUtil.getInstance().mActivityStack) {
                for (Activity act : ActivityUtil.getInstance().mActivityStack) {
                    act.finish();
                }
            }
        }


    }

    //获取context方法
    public static Context getContext(){
        return context;
    }

}

